using System.Collections;
using UnityEngine;
using System;
using UnityEngine.Networking;

namespace Utils.Coroutine
{
    public static class WebRequestExtender
    {
        /// <summary>
        /// 下载文本
        /// </summary>
        /// <param name="actionQueue"></param>
        /// <param name="url"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public static ActionQueue DownloadText(this ActionQueue actionQueue, string url, Action<string> callback)
        {
            return actionQueue.Append(DownloadTextCondition(url, callback));
        }

        private static IEnumerator DownloadTextCondition(string url, Action<string> callback)
        {
            UnityWebRequest www = UnityWebRequest.Get(url);
            yield return www.SendWebRequest();
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.LogWarning($"下载文本失败: {www.error}，URL: {www.url}");
            }
            else
            {
                string text = www.downloadHandler.text;
                callback?.Invoke(text);
            }
        }
    }
}